package com.lap.starter.adapter.driven;

import com.lap.framework.annotation.NotAuth;
import com.lap.service.starter.api.ApiResource;
import com.lap.service.starter.api.builder.ApiScanner;
import com.lap.starter.application.ApiClientAppService;
import com.lap.starter.application.command.UploadApiCmd;
import com.lap.starter.application.dto.Api;
import com.lap.starter.application.dto.ApiClientDto;
import com.lap.watchdog.starter.annotation.RepeatSubmit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "API资源管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("api/v1/apis")
public class ApiController {

  @Resource private ApiClientAppService apiClientAppService;

  @Operation(summary = "Api上报")
  @NotAuth
  @RepeatSubmit
  @PostMapping("local")
  public void uploadApi(@RequestBody UploadApiCmd cmd) {
    List<ApiResource> list = ApiScanner.scan(cmd.getModule(), cmd.getName());
    List<Api> apis = toDtoList(list, cmd.getViewType());

    apiClientAppService.createApi(new ApiClientDto(cmd.getModule(), apis));
  }

  private List<Api> toDtoList(List<ApiResource> list, Integer viewType) {
    return list.stream().map(item -> toDto(item, viewType)).toList();
  }

  private Api toDto(ApiResource apiResource, Integer viewType) {
    return Api.builder()
        .module(apiResource.getModule())
        .code(apiResource.getCode())
        .name(apiResource.getName())
        .parentCode(apiResource.getParentCode())
        .method(apiResource.getMethod())
        .uri(apiResource.getUri())
        .apiType(apiResource.getType().getCode())
        .viewType(viewType)
        .accessLevel(apiResource.getAccessLevel().getCode())
        .build();
  }
}
